/**
 * Created by gzf on 2015/10/9.
 */
user_config = {
    currPageNo:1,
    canNext:true
}

function addMessage(pageNo){
    isLoading(true);
    $.getJSON('msg.json?pageNo='+ pageNo,function(data){
        dealMsgData(data);
    });
}
function dealMsgData(msgJson){
    if(msgJson.status){
        var html = '';
        for(var i= 0,msgList=msgJson.data.data,len=msgList.length;i<len;i++){
            html += '<li class="list-group-item">'
                +       '<dl>'
                +           '<dt>' + msgList[i].content + '</dt>'
                +           '<dd>' + msgList[i].created_at + '</dd>'
                +       '</dl>'
                +       '<div class="del-icon" onclick="delMessage(' + msgList[i].id + ')"></div>'
                +   '</li>';
        }
        setTimeout(function(){
            $('.message-detail-list').append($(html));
            isLoading(false);
        },1000);
    }else{
        setTimeout(function(){
            showMessage(msgJson.msg);
            isLoading(false);
            user_config.currPageNo--;
        },1000);
    }
}
function isLoading(flag){
    if(flag){
        user_config.canNext = false;
        $('.my-message .load-add').addClass('load-adding').text('正在加载...');
    }else{
        user_config.canNext = true;
        $('.my-message .load-add').removeClass('load-adding').text('加载更多');
    }
}
function delMessage(id){
    swal({
        title:'',
        text:'您确认删除么？',
        confirmButtonColor:"#DD6B55",
        confirmButtonText:"确定",
        cancelButtonText:"取消",
        showCancelButton:true,
        closeOnConfirm:false,
        closeOnCancel:false,
        showLoaderOnConfirm:true
    },function(e){e ? delMsgById(id) : swal.close();});
    $('.sweet-alert').css('height','100px');
    $('.sweet-alert p').css('font-size','14px');
}

function delMsgById(id){
    $.ajax({
        url:'deleteMyMessage.php',
        type:'POST',
        dataType:'text',
        data:{messageId:id},
        success:function(){window.location.reload();},
        error:function(){
            $('.sweet-alert').css('height','63px');
            $('.sweet-alert p').css('font-size','13px');
            showMessage('删除失败，请重试');
        }
    });
}

function showMessage(message){
    var content = {};
    content.title = '';
    content.text = message;
    content.animation = 'slide-from-bottom';
    content.timer = 1000;
    content.showConfirmButton = false;
    swal(content);
}

var addMore = $('.my-message .load-add').hammer();
addMore.on('tap',function(){
    if(user_config.canNext){
        addMessage(++user_config.currPageNo);
    }
});

var msgRefresh = $('.glyphicon-refresh').hammer();
msgRefresh.on('tap',function(){
   window.location.reload();
});

